package util

import (
	"fmt"
	"ops.alert.center.service/internal/middleware"
	"ops.alert.center.service/internal/model"
	"strconv"
	"strings"
	"time"
)

func Yunweiwayspause(pause bool, name string) {
	ThisAlertObject := &model.Alertways{}
	middleware.DB.Model(ThisAlertObject).Where("name=?", name).Update("yunwei_pause", pause)
}

func Alertwayspause(pause bool, name string) {
	ThisAlertObject := &model.Alertways{}
	middleware.DB.Model(ThisAlertObject).Where("name=?", name).Update("pause", pause)
}

func Alertwaysget() (model.Way_inserface, bool) {
	alerwaydatas := make([]model.Alertways, 0)
	middleware.DB.Find(&alerwaydatas)
	for index, _ := range alerwaydatas {
		(alerwaydatas)[index].ID = (alerwaydatas)[index].Way_id
	}
	p := model.Way_inserface{
		Datas: alerwaydatas,
	}
	return p, true
}

func DeleteSubscriptionByID(sub_id int) bool {
	ThisAlertsubobject := &model.Alertsubscription{}
	middleware.DB.Where("sub_id=?", sub_id).Delete(ThisAlertsubobject)
	return true
}

func InsertSource(source string, eventOccurTimestamp int64) bool {
	middleware.DB.Table("alertsource").Create(&model.Alertsource{Source: source, EventOccurTimestamp: eventOccurTimestamp})
	return true
}

func UpdateSubscriptionFocusByID(sub_id int, focus bool) bool {
	ThisAlertsubobject := &model.Alertsubscription{}
	middleware.DB.Model(ThisAlertsubobject).Where("sub_id=?", sub_id).Update("focus", focus)
	return true
}

func UpdateSubscriptionPaueByID(sub_id int, focus bool) bool {
	ThisAlertsubobject := &model.Alertsubscription{}
	middleware.DB.Model(ThisAlertsubobject).Where("sub_id=?", sub_id).Update("pause", focus)
	return true
}

func UpdateSubscriptionCount(appname, username string, count int) bool {
	fmt.Println("传进来的数据是", appname, username, count)
	var app_id, contact_id int
	for _, zhaoapplication := range middleware.ThisZhaoapplication {
		if appname == zhaoapplication.Name {
			app_id = zhaoapplication.App_id
		}
	}
	for _, alertcontact := range middleware.ThisAlertcontact {
		if strings.Contains(alertcontact.Email, username) {
			contact_id = alertcontact.Contact_id
		}
	}
	fmt.Println("传进来的数据是", app_id, contact_id, count)
	ThisAlertsubobject := &model.Alertsubscription{}
	middleware.DB.Model(ThisAlertsubobject).Where("app_id=? and contact_id =? ", app_id, contact_id).Update("count", count)
	return true
}

func UpdateSubscriptionblackwords(appname, username, blackwords string) bool {
	var app_id, contact_id int
	var oldBlackwords string
	for _, zhaoapplication := range middleware.ThisZhaoapplication {
		if appname == zhaoapplication.Name {
			app_id = zhaoapplication.App_id
		}
	}
	for _, alertcontact := range middleware.ThisAlertcontact {
		if strings.Contains(alertcontact.Email, username) {
			contact_id = alertcontact.Contact_id
		}
	}
	for _, alertsubscription := range middleware.ThisAlertsubscriptions {
		if alertsubscription.App_id == app_id && alertsubscription.Contact_id == contact_id {
			oldBlackwords = alertsubscription.Black_words
		}
	}
	ThisAlertsubobject := &model.Alertsubscription{}
	middleware.DB.Model(ThisAlertsubobject).Where("app_id=? and contact_id =? ", app_id, contact_id).Update("black_words", oldBlackwords+";"+blackwords)
	return true
}

func UpdateSubdelteblackwords(appname, username, blackwords string) bool {
	var app_id, contact_id int
	var oldBlackwords string
	for _, zhaoapplication := range middleware.ThisZhaoapplication {
		if appname == zhaoapplication.Name {
			app_id = zhaoapplication.App_id
		}
	}
	for _, alertcontact := range middleware.ThisAlertcontact {
		if strings.Contains(alertcontact.Email, username) {
			contact_id = alertcontact.Contact_id
		}
	}
	for _, alertsubscription := range middleware.ThisAlertsubscriptions {
		if alertsubscription.App_id == app_id && alertsubscription.Contact_id == contact_id {
			oldBlackwords = alertsubscription.Black_words
		}
	}
	oldblackwordsslice := strings.Split(oldBlackwords, ";")
	var newblackwords string
	for _, s := range oldblackwordsslice {
		if s == blackwords {
			continue
		} else {
			if len(s) > 0 {
				newblackwords = newblackwords + s + ";"
			}
		}
	}
	ThisAlertsubobject := &model.Alertsubscription{}
	middleware.DB.Model(ThisAlertsubobject).Where("app_id=? and contact_id =? ", app_id, contact_id).Update("black_words", newblackwords)
	return true
}

func SubsriptionAdd(appname, username string, wayids []string) bool {
	var app_id, contact_id int
	var way_ids string

	for _, zhaoapplication := range middleware.ThisZhaoapplication {
		if appname == zhaoapplication.Name {
			app_id = zhaoapplication.App_id
		}
	}
	if app_id == 0 {
		//将app_name塞入找钢的应用
		Thisappobject := &model.Zhaoapplication{}
		Thisappobject.Name = appname
		middleware.DB.Table("zhaoapplication").Create(Thisappobject)
		middleware.GetZhaoapplicatinAllData()
		for _, zhaoapplication := range middleware.ThisZhaoapplication {
			if appname == zhaoapplication.Name {
				app_id = zhaoapplication.App_id
			}
		}
	}
	for _, alertcontact := range middleware.ThisAlertcontact {
		if strings.Contains(alertcontact.Email, username) {
			contact_id = alertcontact.Contact_id
		}
	}
	for _, way := range middleware.ThisAlertways {
		for _, thisway := range wayids {
			if way.Name == thisway {
				way_ids = way_ids + strconv.Itoa(way.Way_id) + ","
			}
		}
	}
	fmt.Println("插入的数据是", app_id, contact_id, way_ids)
	ThisAlertsubobject := &model.Alertsubscription{}
	ThisAlertsubobject.App_id = app_id
	ThisAlertsubobject.Contact_id = contact_id
	ThisAlertsubobject.Pause = false
	ThisAlertsubobject.Way_ids = way_ids
	ThisAlertsubobject.Focus = false
	ThisAlertsubobject.Black_words = "无"
	ThisAlertsubobject.Count = 30
	middleware.DB.Table("alertsubscription").Create(ThisAlertsubobject)
	return true
}

//func GetSendHistory(shouldtable string) bool {
//	ThisAlertsubobject := &model.Alertsubscription{}
//	middleware.DB.Where("sub_id=?", sub_id).Delete(ThisAlertsubobject)
//	return true
//}

func SearchTablehave(table string) bool {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("SearchTablehave error", err)
		}
	}()
	row, err := middleware.DBSQl.Query("SELECT * FROM " + table)
	defer row.Close()
	if err != nil {
		return false
	}
	return true
}

func CreateTable(table string) {
	sql := `
    CREATE TABLE ` + table + `(
        eventOccurTimestamp BIGINT,
        app_id INT NOT NULL,
        contact_id INT NOT NULL,
        words VARCHAR(100) NOT NULL,
        way_ids   VARCHAR(100) 
    )ENGINE=InnoDB DEFAULT CHARSET=utf8;`

	tx, err := middleware.DBSQl.Begin()
	if err != nil {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "CreateTable tx fail")
	}
	stmt, err := tx.Prepare(sql)
	defer stmt.Close()
	if err != nil {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "Prepare fail CreateTable err", err)
	}
	_, err3 := stmt.Exec()
	if err3 != nil {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "CreateTable Exec fail")
	}
	tx.Commit()
}

//添加告警历史数据
func AlertHistoryAdd(contact_id, app_id int, eventOccurTimestamp int64, words, way_ids, Should_table string) error {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("AlertHistoryAdd err", err)
		}
	}()
	tx, err := middleware.DBSQl.Begin()
	if err != nil {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "AlertHistoryAdd tx fail")
		return err
	}
	//准备sql语句
	Query_words := fmt.Sprintf("INSERT INTO " + Should_table + " (eventOccurTimestamp,app_id,contact_id,words,way_ids) VALUES (" + strconv.FormatInt(eventOccurTimestamp, 10) + "," + strconv.Itoa(app_id) + "," + strconv.Itoa(contact_id) + ",'" + words)
	Query_words = Query_words + "'" + "," + "'" + way_ids + "'" + ")"
	stmt, err := tx.Prepare(Query_words)
	if err != nil {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "Prepare fail AlertHistoryAdd  err", err)
		return err
	}
	//将参数传递到sql语句中并且执行
	res, err := stmt.Exec()
	if err != nil {
		fmt.Println(time.Now().Format("2006-01-02 15:04:05"), "AlertHistoryAdd Exec fail")
		return err
	}
	//提交事务
	tx.Commit()
	stmt.Close()
	fmt.Println(res.LastInsertId())
	return nil
}

//查询一分钟内发送的次数
func SearchAlertHistoryimes(contact_id, app_id int, eventOccurTimestamp int64, words, Should_table string) (Count int) {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("SearchAlertHistoryimes err", err)
		}
	}()

	var This_eventOccurTimestamp int64
	Query_words := fmt.Sprintf("SELECT eventOccurTimestamp FROM %s  where app_id =%d  and contact_id =%d  and words ='%s'", Should_table, app_id, contact_id, words)
	rows, err := middleware.DBSQl.Query(Query_words)
	if err != nil {
		fmt.Println("search  "+Should_table+" one minute", err)
	}
	for rows.Next() {
		err := rows.Scan(&This_eventOccurTimestamp)
		if eventOccurTimestamp-This_eventOccurTimestamp < 60 {
			Count += 1
		}
		if err != nil {
			fmt.Println("rows fail")
		}
	}
	return
}
